<template>
    <div class="container">
        <!-- 搜索栏 -->
        <div class="header">
            <el-form inline class="searchItem">
                <div style="display: flex">
                    <el-form-item label="能耗指标">
                        <el-select
                            v-model="searchForm.indexType"
                            placeholder="请选择能耗指标"
                            size="small"
                        >
                            <el-option
                                v-for="item in indexTypeOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="时间粒度">
                        <el-select
                            v-model="searchForm.timeGrain"
                            size="small"
                            @change="handleTimeGrainChange"
                        >
                            <el-option
                                v-for="item in timeGrainOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="时间范围">
                        <template v-if="searchForm.timeGrain !== 'year'">
                            <el-date-picker
                                v-model="searchForm.dateRange"
                                :type="datePickerType"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                :picker-options="pickerOptions"
                                value-format="yyyy-MM-dd"
                                size="small"
                            />
                        </template>
                        <template v-else>
                            <el-select
                                v-model="searchForm.yearList"
                                multiple
                                placeholder="请选择年份"
                                size="small"
                                :collapse-tags="true"
                                :max-collapse-tags="3"
                            >
                                <el-option
                                    v-for="year in yearList"
                                    :key="year"
                                    :label="year"
                                    :value="year"
                                />
                            </el-select>
                        </template>
                    </el-form-item>
                </div>
                <div style="display: flex">
                    <el-form-item>
                        <el-button
                            size="small"
                            type="primary"
                            @click="handleSearch"
                            icon="el-icon-search"
                            >查询</el-button
                        >
                        <el-button
                            size="small"
                            type="warning"
                            @click="handleReset"
                            icon="el-icon-refresh-left"
                            >重置</el-button
                        >
                        <el-button
                            size="small"
                            type="success"
                            @click="handleExport"
                            icon="el-icon-download"
                            >导出</el-button
                        >
                    </el-form-item>
                </div>
            </el-form>
        </div>

        <!-- 主体内容 -->
        <div class="main energy-analysis" v-loading="loading" element-loading-text="数据加载中...">
            <!-- 指标统计模块 -->
            <div class="stats-cards">
                <div class="stats-card" v-for="(item, index) in statsCards" :key="index">
                    <div class="stats-card-content">
                        <div class="icon-section">
                            <svg-icon :icon-class="item.icon" />
                        </div>
                        <div class="info-section">
                            <div
                                class="card-value"
                                :class="{
                                    red: item.isPositive === true,
                                    green: item.isPositive === false,
                                }"
                            >
                                {{ item.value }}
                            </div>
                            <div class="card-title">
                                {{ item.title }}
                                <span class="card-unit">({{ item.unit }})</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="chart-box">
                <!-- 能耗指标对标曲线图 -->
                <div class="chart-container" style="flex: 2">
                    <LineChart :chart-data="chartData" :time-grain="searchForm.timeGrain" />
                </div>

                <!-- 能耗指标对标环状图 -->
                <div class="chart-container pie-bg" style="flex: 1">
                    <PieChart :table-data="tableData" :time-granularity="searchForm.timeGrain" />
                </div>
            </div>

            <!-- 能耗指标对标数据报表 -->
            <RlTable :search="false" :is-pagination="true" @on-change="loadTableData" ref="rlTable">
                <template #default>
                    <el-table-column prop="date" label="时间" />
                    <el-table-column prop="indexValue" :label="`${getIndexLabel}(kWh/m²)`" />
                    <el-table-column prop="benchmarkValue" label="数据标杆值(kWh/m²)" />
                    <el-table-column prop="constraintValue" label="数据约束值(kWh/m²)" />
                    <el-table-column prop="benchmarkDiff" label="数据标杆值差(kWh/m²)">
                        <template slot-scope="scope">
                            <span :style="{ color: getDiffColor(scope.row.benchmarkDiff) }">
                                {{ formatDiffValue(scope.row.benchmarkDiff) }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="constraintDiff" label="数据约束值差(kWh/m²)">
                        <template slot-scope="scope">
                            <span :style="{ color: getDiffColor(scope.row.constraintDiff) }">
                                {{ formatDiffValue(scope.row.constraintDiff) }}
                            </span>
                        </template>
                    </el-table-column>
                </template>
            </RlTable>
        </div>
    </div>
</template>

<script>
    import LineChart from './components/LineChart.vue'
    import PieChart from './components/PieChart.vue'
    import { getEnergyData, exportEnergyData } from '@/api/energy'
    import dayjs from 'dayjs'

    // 格式化数字,保留2位小数
    const formatNumber = (num) => {
        return num === null || num === undefined ? defaultValue : Number(num).toFixed(2)
    }

    export default {
        name: 'EnergyAnalysis',
        components: {
            LineChart,
            PieChart,
        },
        props: {
            mallType: {
                type: String,
                required: true,
            },
        },
        data() {
            return {
                loading: false,
                searchForm: {
                    indexType: 'cooling',
                    timeGrain: 'month',
                    dateRange: [],
                    yearList: [],
                },
                // 能耗指标选项
                indexTypeOptions: [
                    { label: '制冷系统能耗强度指标', value: 'cooling' },
                    { label: '空调末端能耗指标', value: 'terminal' },
                ],
                // 时间粒度选项
                timeGrainOptions: [
                    { label: '日', value: 'day' },
                    { label: '月', value: 'month' },
                    { label: '年', value: 'year' },
                ],
                // 可用的年份数据
                yearList: [2024, 2023],
                pickerOptions: {
                    disabledDate: (time) => {
                        return time.getTime() > Date.now()
                    },
                    onPick: ({ maxDate, minDate }) => {
                        if (maxDate && minDate) {
                            const diffTime = maxDate.getTime() - minDate.getTime()
                            const timeGrain = this.searchForm.timeGrain

                            if (timeGrain === 'day' && diffTime > 60 * 24 * 60 * 60 * 1000) {
                                this.$message.warning('日期范围最多选择60天')
                                this.searchForm.dateRange = []
                                return false
                            }

                            if (timeGrain === 'month') {
                                const months =
                                    (maxDate.getFullYear() - minDate.getFullYear()) * 12 +
                                    maxDate.getMonth() -
                                    minDate.getMonth()
                                if (months > 48) {
                                    this.$message.warning('日期范围最多选择48个月')
                                    this.searchForm.dateRange = []
                                    return false
                                }
                            }
                        }
                    },
                },
                statsCards: [],
                chartData: {
                    dates: [],
                    values: [],
                    benchmark: [],
                    constraint: [],
                },
                tableData: [],
            }
        },
        computed: {
            datePickerType() {
                const typeMap = {
                    day: 'daterange',
                    month: 'monthrange',
                    year: 'years',
                }
                return typeMap[this.searchForm.timeGrain]
            },
            getIndexLabel() {
                return this.searchForm.indexType === 'cooling'
                    ? '制冷系统能耗强度指标'
                    : '空调末端能耗指标'
            },
        },
        watch: {
            mallType: {
                handler(newVal) {
                    this.handleSearch()
                },
                immediate: true,
            },
        },
        mounted() {
            this.setDefaultDateRange()
        },
        methods: {
            handleSearch() {
                this.$nextTick(() => {
                    const rlTable = this.$refs.rlTable
                    if (rlTable) {
                        rlTable.onSearchChange()
                    }
                })
            },

            handleReset() {
                this.searchForm.indexType = 'cooling'
                this.searchForm.timeGrain = 'month'
                this.setDefaultDateRange()
                this.handleSearch()
            },

            async loadTableData({ resolve, params }) {
                this.loading = true
                try {
                    const requestParams = {
                        mallType: this.mallType,
                        ...this.searchForm,
                        ...params,
                    }

                    const isYear = this.searchForm.timeGrain === 'year'
                    const isMonth = this.searchForm.timeGrain === 'month'

                    // 如果是年份查询，使用yearList替代dateRange
                    if (isYear) {
                        requestParams.dateRange = this.searchForm.yearList.map(
                            (year) => `${year}-01-01`
                        )
                    }

                    console.log('requestParams', requestParams)

                    const res = await getEnergyData(requestParams)

                    if (res.code === '200') {
                        this.chartData = res.data.chartData
                        this.tableData = res.data.tableData.map((item) => ({
                            ...item,
                            date: isYear
                                ? dayjs(item.date).format('YYYY')
                                : isMonth
                                  ? dayjs(item.date).format('YYYY-MM')
                                  : dayjs(item.date).format('YYYY-MM-DD'),
                        }))
                        this.updateStats(res.data)

                        resolve({
                            records: this.tableData || [],
                            total: res.data.total || 0,
                        })
                    } else {
                        resolve({
                            records: [],
                            total: 0,
                        })
                    }
                } catch (error) {
                    console.error('获取数据失败：', error)
                    resolve({
                        records: [],
                        total: 0,
                    })
                } finally {
                    this.loading = false
                }
            },

            async handleExport() {
                try {
                    const res = await exportEnergyData({
                        mallType: this.mallType,
                        ...this.searchForm,
                    })

                    if (res.code === '200') {
                        const blob = new Blob([res.data], {
                            type: 'application/vnd.ms-excel',
                        })
                        const url = window.URL.createObjectURL(blob)
                        const link = document.createElement('a')
                        link.href = url
                        link.download = `能耗指标分析_${dayjs().format('YYYY/MM/DD')}.xlsx`
                        link.click()
                        window.URL.revokeObjectURL(url)
                    } else {
                        this.$message.error(res.message || '导出失败')
                    }
                } catch (error) {
                    console.error('导出失败：', error)
                    this.$message.error('导出失败，请重试')
                }
            },

            handleTimeGrainChange() {
                if (this.searchForm.timeGrain === 'year') {
                    this.searchForm.dateRange = []
                    this.searchForm.yearList = [this.yearList[0]]
                } else {
                    this.searchForm.yearList = []
                    this.setDefaultDateRange()
                }
            },

            handleDateChange() {
                this.handleSearch()
            },

            setDefaultDateRange() {
                const end = new Date()
                const start = new Date()

                switch (this.searchForm.timeGrain) {
                    case 'day':
                        start.setDate(end.getDate() - 30)
                        break
                    case 'month':
                        start.setMonth(end.getMonth() - 12)
                        break
                    case 'year':
                        // TODO：年份不设置默认范围，由后端返回可用年份,禁用没有数据的年份
                        this.searchForm.dateRange = ['2024-01-01']
                        return
                }

                // 格式化日期为 yyyy-MM-dd
                const formatDate = (date) => {
                    const year = date.getFullYear()
                    const month = String(date.getMonth() + 1).padStart(2, '0')
                    const day = String(date.getDate()).padStart(2, '0')
                    return `${year}-${month}-${day}`
                }

                this.searchForm.dateRange = [formatDate(start), formatDate(end)]
            },

            formatDiffValue(value) {
                const numValue = Number(value)
                const arrow = numValue >= 0 ? '↑ ' : '↓ '
                return `${arrow}${Math.abs(numValue)}`
            },

            getDiffColor(value) {
                return Number(value) >= 0 ? '#f56c6c' : '#67c23a'
            },

            updateStats(data) {
                // 确保data和data.stats存在
                if (!data || !data.stats) {
                    console.warn('数据格式错误')
                    return
                }

                const stats = data.stats

                this.statsCards = [
                    {
                        title: '当前指标值',
                        value: formatNumber(stats.currentValue),
                        unit: 'kWh/m²',
                        isPositive: null,
                        icon: 'trend',
                    },
                    {
                        title: '数据标杆值',
                        value: formatNumber(stats.benchmarkValue),
                        unit: 'kWh/m²',
                        isPositive: null,
                        icon: 'lightning',
                    },
                    {
                        title: '数据约束值',
                        value: formatNumber(stats.constraintValue),
                        unit: 'kWh/m²',
                        isPositive: null,
                        icon: 'lightning',
                    },
                    {
                        title: '数据标杆值差',
                        value: stats.benchmarkDiff
                            ? (Number(stats.benchmarkDiff) >= 0 ? '+' : '') +
                              formatNumber(stats.benchmarkDiff)
                            : formatNumber(stats.benchmarkDiff),
                        unit: 'kWh/m²',
                        isPositive: stats.benchmarkDiff ? Number(stats.benchmarkDiff) >= 0 : false,
                        icon: 'lightning',
                    },
                    {
                        title: '数据约束值差',
                        value: stats.constraintDiff
                            ? (Number(stats.constraintDiff) >= 0 ? '+' : '') +
                              formatNumber(stats.constraintDiff)
                            : formatNumber(stats.constraintDiff),
                        unit: 'kWh/m²',
                        isPositive: stats.constraintDiff
                            ? Number(stats.constraintDiff) >= 0
                            : false,
                        icon: 'lightning',
                    },
                ]
            },
        },
    }
</script>

<style lang="scss" scoped>
    // 变量定义
    $primary-blue: #009cff;
    $primary-bg: #0c2e64;
    $card-bg: #00235c;
    $text-white: #ffffff;
    $text-cyan: #00ffff;
    $text-red: #f56c6c;
    $text-green: #67c23a;
    $border-radius: 10px;
    $spacing-base: 20px;

    // 通用样式
    %flex-center {
        display: flex;
        align-items: center;
    }

    %flex-between {
        display: flex;
        justify-content: space-between;
    }

    // 头部样式
    .header {
        height: 36px;
        background-color: $primary-bg;
        border-radius: 6px;
        padding: $spacing-base 15px;
        @extend %flex-center;

        .searchItem {
            height: 100%;
            width: 100%;
            @extend %flex-center;
            @extend %flex-between;

            & > div {
                height: 100%;
            }
        }
    }

    // 主体内容
    .energy-analysis {
        padding: $spacing-base;

        .search-bar {
            margin-bottom: $spacing-base;

            .el-select {
                margin-right: 15px;
            }
        }

        // 统计卡片
        .stats-cards {
            margin-bottom: $spacing-base;
            display: flex;
            justify-content: space-around;

            .stats-card {
                background: $card-bg;
                box-shadow: inset 0px 0px 27px 0px $primary-blue;
                border-radius: $border-radius;
                @extend %flex-center;
                flex: 1;
                margin: 0 5px;
                border-image: linear-gradient(
                        360deg,
                        rgba(3, 102, 186, 1),
                        rgba(0, 221, 255, 0.89),
                        rgba(3, 102, 186, 1)
                    )
                    2 2;

                .stats-card-content {
                    height: 100%;
                    @extend %flex-center;
                    padding: $spacing-base;

                    .icon-section {
                        margin-right: $spacing-base;
                        font-size: 80px;

                        i {
                            font-size: 40px;
                            color: $primary-blue;
                        }
                    }

                    .info-section {
                        display: flex;
                        flex-direction: column;

                        .card-value {
                            font-size: 24px;
                            font-weight: bold;
                            margin-bottom: 8px;
                            color: $text-cyan;

                            &.red {
                                color: $text-red;
                            }
                            &.green {
                                color: $text-green;
                            }

                            .card-unit {
                                font-size: 12px;
                                margin-left: 4px;
                            }
                        }

                        .card-title {
                            color: $text-white;
                            font-size: 14px;
                        }
                    }
                }
            }
        }

        // 图表区域
        .chart-box {
            display: flex;
            height: 350px;
            margin-bottom: $spacing-base;

            .chart-container {
                height: 100%;
            }
        }

        .pie-bg {
            background: #{$primary-bg}22;
            border-radius: $border-radius;
            margin-left: 10px;
        }
    }

    ::v-deep .el-loading-mask {
        background: #{$text-white}33 !important;
    }
</style>
